package com.alibaba.otter.manager.web.utils;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;

import java.util.Set;

/**
 * @Auther: lic
 * @Date: 2023/2/14 - 02 - 14 - 15:32
 * @Description: com.pft.common.core.utils
 * @version: 1.0
 */
public class BeanValidator {

    private static final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    private BeanValidator() {}

    /**
     * 校验对象
     */
    public static String validate(Object t, Class<?>... groups) {
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<Object>> validateResult = validator.validate(t, groups);
        if (validateResult.isEmpty()) {
            return "";
        }

        StringBuilder errors = new StringBuilder();
        for (ConstraintViolation<Object> violation : validateResult) {
            errors.append(violation.getMessage()).append(",");
        }
        if (!errors.isEmpty()) {
            return errors.substring(0, errors.length() - 1);
        }
        return errors.toString();
    }
}